// ==UserScript==
// @name         GPA Calculator
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Calculate GPA from table data
// @author       hj-x and ChatGPT3.5
// @match        *://yjsjy.webvpn.cufe.edu.cn/yjsxt/cjcx/*
// @match        *://yjsjy.cufe.edu.cn/yjsxt/cjcx/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Function to calculate GPA
    function calculateGPA() {
        const rows = document.querySelectorAll('#tabGrid tbody tr.ui-widget-content');
        let totalCredits = 0, totalPoints = 0;
        let compulsoryCredits = 0, compulsoryPoints = 0;
        let electiveCredits = 0, electivePoints = 0;
        let totalGradeSum = 0, compulsoryGradeSum = 0, electiveGradeSum = 0;

        rows.forEach(row => {
            const type = row.querySelector('[aria-describedby="tabGrid_kcxzmc"]').textContent.trim();
            const credits = parseFloat(row.querySelector('[aria-describedby="tabGrid_xf"]').textContent.trim());
            const grade = parseFloat(row.querySelector('[aria-describedby="tabGrid_cj"]').textContent.trim());
            const gpa = parseFloat(row.querySelector('[aria-describedby="tabGrid_jd"]').textContent.trim());

            if (type === "必修课") {
                compulsoryCredits += credits;
                compulsoryPoints += gpa * credits;
                compulsoryGradeSum += grade * credits;
            } else if (type === "选修课") {
                electiveCredits += credits;
                electivePoints += gpa * credits;
                electiveGradeSum += grade * credits;
            }

            totalCredits += credits;
            totalPoints += gpa * credits;
            totalGradeSum += grade * credits;
        });

        const totalGPA = totalPoints / totalCredits;
        const compulsoryGPA = compulsoryPoints / compulsoryCredits;
        const electiveGPA = electivePoints / electiveCredits;
        const totalAvg = totalGradeSum / totalCredits;
        const compulsoryAvg = compulsoryGradeSum / compulsoryCredits;
        const electiveAvg = electiveGradeSum / electiveCredits;

        alert(`总均分: ${totalAvg.toFixed(6)}\n总绩点: ${totalGPA.toFixed(6)}\n必修均分: ${compulsoryAvg.toFixed(6)}\n必修绩点: ${compulsoryGPA.toFixed(6)}\n选修均分: ${electiveAvg.toFixed(6)}\n选修绩点: ${electiveGPA.toFixed(6)}`);
    }

    // Add a button to trigger GPA calculation
    const button = document.createElement('button');
    button.textContent = '计算绩点';
    button.style.position = 'fixed';
    button.style.top = '10px';
    button.style.right = '10px';
    button.style.zIndex = 1000;
    button.onclick = calculateGPA;
    document.body.appendChild(button);
})();
